package FlowGram.Application.Parser.Actions.Control;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import FlowGram.Application.Parser.FinchParser;
import FlowGram.Application.Parser.FinchParserException;
import FlowGram.Application.Parser.Actions.Property.PropertyAction;
import FlowGram.Application.Parser.Controllers.FinchController;


/**
 * 
 * @author thackray
 *
 */
public class While extends ControlAction {

	
	protected PropertyAction property;
	
	public While(FinchParser parser) {
		super(parser);
	}	
	public While() {
		super();
	}	
	public void setProperty(PropertyAction prop){
		this.property = prop;
	}
	public PropertyAction getProperty(){
		return this.property;
	}
	public static boolean matches(String s){
		return s.matches("^while.+");
	}
	public static boolean matchesEnd(String s){
		return s.matches("^endwhile$");
	}
	public static String syntax(){
		return "while <condition>\n\t<code>\nendwhile";
	}
	
	@Override
	public String toCode(int indent) {
		return "while "+this.property.toCode()+"\n"+this.innerFlow.toCode(indent+1)+"\n"+this.getIndent(indent)+"endwhile";
	}
	@Override
	public String toHTML(String idPrefix) {
		return "while "+this.property.toHTML(idPrefix)+"\n\t"+this.innerFlow.toHTML(idPrefix)+"\nendwhile";
	}

	@Override
	public void execute(FinchController controller) {
		this.ensureController(controller);
		while(this.property.getValue(controller)){
			this.innerFlow.execute();
		}

	}

	@Override
	public String logMessage() {
		return "while "+this.property.logMessage();
	}

	@Override
	public void parse(String statement) throws FinchParserException {
		Pattern p = Pattern.compile("^while\\s+(\\w+)$");
		Matcher matcher = p.matcher(statement);
		while(matcher.find()){
			if(matcher.group(1) != null){
				this.property = PropertyAction.findProperty(matcher.group(1));
				String buffer = "";
				String line = this.parser.getNextStatement();
				int sawwhile = 0;
				while(true){
					if(matchesEnd(line)){
						if(sawwhile == 0){
							break;
						}
						sawwhile--;
					}
					if(matches(line)){
						sawwhile++;
					}
					buffer += line+"\n";
					line = this.parser.getNextStatement();
				}
				FinchParser parse = new FinchParser();
				this.innerFlow = parse.Parse(buffer);
			}	
		}
	}

}
